package face.pay.task.order.api;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.face.pay.AliPayConfig;
import face.pay.dao.EnterpriseInfoDao;
import face.pay.dao.OrderInfoDao;
import face.pay.entity.EnterpriseInfo;
import face.pay.entity.OemInfo;
import face.pay.entity.OrderInfo;
import face.pay.task.order.message.MessageSender;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 结构查询
 */
@Slf4j
@Component
public class ApiAliOrderQuery extends  AbstractApi {

    @Autowired
    private OrderInfoDao orderInfoDao;

    @Autowired
    private EnterpriseInfoDao enterpriseInfoDao;



    @Async
    public void orderStatusCheck(OrderInfo orderInfo, AliPayConfig aliPayConfig) {


        try{
            Integer i = 0;

            Long orderId = orderInfo.getId();


                String trade_no = orderInfo.getTradeNo();
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",aliPayConfig.getAppid(),aliPayConfig.getAppKey(),"json","utf-8",aliPayConfig.getAliPublicKey(),"RSA2");
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

                EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryByUserId(orderInfo.getUserId());

                Map<String,Object> params = new HashMap<>();
                if(StringUtils.isNotBlank(trade_no)){
                    params.put("trade_no",trade_no);
                }

                params.put("out_trade_no",String.valueOf(orderInfo.getId()));

                String query_options[] =  new String[]{"TRADE_SETTE_INFO"};

                params.put("query_options",query_options);

                request.setBizContent(JSON.toJSONString(params));
                request.putOtherTextParam("app_auth_token",enterpriseInfo.getAliToken());

                AlipayTradeQueryResponse response = alipayClient.execute(request);


                log.info("正在查询：orderid "+orderId);
                log.info("返回结果："+JSON.toJSONString(response));
                if(response.isSuccess()){
                    String trade_status = response.getTradeStatus();
                    switch (trade_status) {
                        case "TRADE_SUCCESS": {
                            //1支付成功(SUCCESS)
                            updateOrderStatus(orderId, 1, "支付成功");
                            orderInfo.setStatus(1);
                            orderInfo.setMessage("支付成功");
                            this.sendAllMessage(orderInfo,aliPayConfig.getOemType());
                            break;
                        }
                        /**
                         * 订单已关闭
                         */
                        case "TRADE_CLOSED": {
                            updateOrderStatus(orderId, -4, "支付超时或取消");
                            break;
                        }

                        //1 交易结束 不可退款
                        case "TRADE_FINISHED": {
                            updateOrderStatus(orderId, 1, "交易已完成");
                            break;
                        }
                        case "WAIT_BUYER_PAY": {
                            /**
                             * 等待买家付款
                             */
                            break;
                        }
                    }
                }
                Thread.sleep(3000);
                i++;


        }catch (Exception e){
            log.info("支付宝订单查询异常",e);
        }


    }


    /**
     * 更新订单状态和信息
     */
    @Transactional
    void updateOrderStatus(Long orderId, Integer status, String message) {
        OrderInfo record = new OrderInfo();
        record.setId(orderId);
        record.setStatus(status);
        record.setMessage(message);
        record.setProfitSign(0);
        this.orderInfoDao.updatePayInfo(record);
    }
}
